import axios from "axios";
import store from "@/store"

const instance = axios.create({
    baseURL: "/api",
    timeout: 5000
})
// 请求拦截器
instance.interceptors.request.use(config => {
    let token = localStorage.getItem("x-auth-token")
    if (token) {
        config.headers["x-auth-token"] = token;
    }
    console.log(token);
    return config
}, err => {
    return Promise.reject(err)
})

// 响应拦截器
instance.interceptors.response.use(res => { // 200
    // console.log("!!!!!~~~~~~~~~~~");
    let ret = res.data;

    if (ret.errCode !== 0) {
        // 提示
        alert(ret.message);
    }

    return ret
}, err => { // 500
    // console.log("78979789789789!!!!!~~~~~~~~~~~");
    // console.log(typeof err)  // object
    // for (var key in err) {
    //     console.log(key, err[key]);
    // }
    // alert(err.response.data.message)
    let action = {
        type: "showAlert",
        value: {
            showAlert: true,
            alertType: "warning",
            alertContent: err.response.data.message
        }
    }
    store.dispatch(action);
    setTimeout(() => {
        store.dispatch({
            type: "hideAlert"
        });
    }, 1500);
    console.log(err.response);
    // 错误码
    if (err.response.data.errCode === 1002) {
        return err    // 直接回到组件中的await继续执行，而 组件中的 res接收这个err对象
    }

    return Promise.reject(err)
})

export default instance